package com.springcloud.sc.ucpv5.client.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ToolUtil {

	// 用Java调用windows系统的exe文件，比如notepad，calc之类
	public static void openWinExe() {
		Runtime rn = Runtime.getRuntime();
		Process p = null;
		try {
			String command = "notepad";
			p = rn.exec(command);
		} catch (Exception e) {
			System.out.println("Error win exec!");
		}
	}

	// 调用其他的可执行文件，例如：自己制作的exe，或是下载安装的软件.
	public static void openExe(String exeName) {
		try {
			Runtime rn = Runtime.getRuntime();
			Process p = null;
			p = rn.exec(exeName);
		} catch (Exception e) {
			e.printStackTrace();
			PublicUtil.debugInfo("打开Exe程序异常结束:" + exeName + "::" + e.getMessage());
		}
	}

	public static boolean isRunning(String processName) {
		BufferedReader bufferedReader = null;
		try {
			Process proc = Runtime.getRuntime().exec("tasklist /FI \"IMAGENAME eq " + processName + "\"");
			bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
			String line = null;
			while ((line = bufferedReader.readLine()) != null) {
				if (line.contains(processName)) // 判断是否存在
				{
					return true;
				}
			}
			return false;
		} catch (Exception ex) {
			ex.printStackTrace();
			return false;
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (Exception ex) {
				}
			}
		}
	}

	public static void closeProcess(String programName) {
		Process listprocess;
		try {
			listprocess = Runtime.getRuntime().exec("cmd.exe /c tasklist");
			InputStream is = listprocess.getInputStream();
			BufferedReader r = new BufferedReader(new InputStreamReader(is));
			// StringBuffer sb = new StringBuffer();
			String str = null;
			while ((str = r.readLine()) != null) {
				String id = null;
				Matcher matcher = Pattern.compile(programName + "[ ]*([0-9]*)").matcher(str);
				while (matcher.find()) {
					if (matcher.groupCount() >= 1) {
						id = matcher.group(1);
						if (id != null) {
							Integer pid = null;
							try {
								pid = Integer.parseInt(id);
							} catch (NumberFormatException e) {
								e.printStackTrace();
							}
							if (pid != null) {
								Runtime.getRuntime().exec("cmd.exe /c taskkill /f /pid " + pid);
								// System.out.println("kill progress"+pid);
							}
						}
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
